import { Toast } from "vant";
import { base } from "@/utils/config";
import axios from "axios";
const request = (url, config) => {
  if (
    url !=
    "/bmt-separate-stock/separate/app/deliver-cargo-bill/query/notice-status"
  ) {
    Toast.loading({
      message: "加载中...",
      forbidClick: true,
    });
  }

  if (url === "/dmsp-oauth/oauth/token") {
    config.headers = {
      ...config.headers,
      Authorization:
        "Basic MDcxYTQ2MDQ2NDMxNDI4ZDkyODliOGE5NThhMjU2NjA6eXNxcWNNSUdSN2NXblZibE5SdnY5Q1FVeVBQOVN3TmR1ZE0=",
    };
  } else {
    config.headers = {
      ...config.headers,
      Authorization: `Bearer ${window.localStorage.getItem("token")}`,
    };
  }
  return new Promise((resolve, reject) => {
    axios(base + url, config)
      .then(
        (resJson) => {
          Toast.clear();
          if (resJson.status == 200) {
            resolve(resJson.data);
          } else {
            Toast(resJson.data.message);
          }
        },
        (err) => {
          if (err.response.status === 401) {
            window.localStorage.clear();
            window.location.href = "/login";
          }
          Toast(err.response.data.message);
          reject(err);
        }
      )
      .catch((error) => {
        throw new Error("服务器异常");
      });
  });
};

export const postFrom = (url, params) => {
  let formData = "";
  if (params) {
    let paramsArray = [];
    Object.keys(params).forEach((key) =>
      paramsArray.push(key + "=" + params[key])
    );
    formData += paramsArray.join("&");
  }
  let config = {
    method: "POST",
    data: formData,
    headers: {
      "Content-Type": "application/x-www-form-urlencoded;charset=utf-8;",
    },
  };
  return request(url, config);
};
// 上传文件
export const postFromFile = (url, params) => {
  let config = {
    method: "POST",
    data: params,
  };
  return request(url, config);
};
// get请求
export const get = (url, params) => {
  if (params) {
    let paramsArray = [];
    Object.keys(params).forEach((key) =>
      paramsArray.push(key + "=" + params[key])
    );
    if (url.search(/\?/) === -1) {
      url += "?" + paramsArray.join("&");
    } else {
      url += "&" + paramsArray.join("&");
    }
  }
  return request(url, {
    method: "GET",
    headers: {
      "Content-Type": "application/json;charset=utf-8;",
    },
  });
};
// post请求
export const post = (url, params) => {
  return request(url, {
    method: "POST",
    data: JSON.stringify(params),
    headers: {
      "Content-Type": "application/json;charset=utf-8;",
    },
  });
};
